import { getSignContract, createWithholdSign, getWithholdSign } from '@/api/leaseOrder.js'
import {tradeCreate} from "../api/order";
export default {
	data() {
		return {
			appId: '',
			orderItem: null,
			// 沙箱：sml，正式：prod
			esignEnv:  'prod',
			esignType: 'SIGN', // 签署 SIGN（默认）, 认证授权 AUTH
			esignPlugin: null,
		}
	},
	onLoad(options) {
		if(options.merchantId && options.orderId && options.tenantId) {
			this.verify_ato_withhold(options.tenantId)
		}
		
		const { miniProgram } = uni.getAccountInfoSync();
		// if(process.env.NODE_ENV == "development") this.esignEnv = 'sml'
		if(miniProgram) this.appId =  miniProgram.appId ? miniProgram.appId : ''
		
		// #ifdef MP-ALIPAY
		this.esignPlugin = requirePlugin("esign");
		// #endif
		/* order_lease.contract_status 合同状态(-1:未生成,0:待签约,1:已签约,2已完成,3已取消)
		order_lease.check_type 核验方式(1:芝麻免押e签宝,2:蚂蚁链租赁合同)
		order_lease.freeze_status 代扣签约/冻结状态(0:未签约冻结,1:签约冻结中,2:已完结,3:已解约取消) */
	},
	onShow() {
		// #ifdef MP-ALIPAY
		const { code, message } = this.esignPlugin.getSignStatusInfo();
		if(code == '000') this.verify_esign_contract()
		// #endif
	},
	methods: {
		ato_withhold(item, url) {
			createWithholdSign(item.id).then(res => {
				uni.navigateToMiniProgram({
					appId:"2021001152620480",
					path:"pages/tripartite/index",
					query:{
						tenantId: item.id,
						merchantId: item.uid,
						orderId: item.order_id,
						signStr:res.data.signStr,
						redirectUrl: `alipays://platformapi/startapp?appId=${this.appId}&page=${url}` 
					},
					complete: (ress) => { uni.hideLoading() },
				});
			}, err => {
				this.verify_ato_withhold(item.id)
			})
		},
		esign_contract(item) {
			this.orderItem = item
			const { order_lease } = item 
			const detail = typeof order_lease.contract_detail == 'string' ? JSON.parse(order_lease.contract_detail) : order_lease.contract_detail
			if( [1,3].includes(order_lease.check_type) ) {
				// 扣款提醒
				this.payTip=true
				this.esignPlugin
					? this.esign_plugin(detail,item.esign_psn_id)
					: this.esign_H5(detail)
			}
			if(order_lease.check_type == 2) {
				let that=this
				//获取当前完整路径
				const pages = getCurrentPages(); // 获取页面栈
				const currentPage = pages[pages.length - 1]; // 当前页面
				// 交易组件
				my.checkBeforeAddOrder({
					success({ requireOrder, sceneId, sourceId }) {
						tradeCreate({
							oid:that.orderInfo.id,
							source_id: sourceId,
							path:'pages/goods/lease_order_details/index'
						}).then(res=>{
							if(res.status===200){
								// 唤起去租赁宝签署
								that.esign_plugin(detail)
							}
						})
					},
					fail({ error, errorMessage }) {
						that.$util.Tips({ title: '订单前置判断失败'})
					},
					complete(e) {
						// console.log(e)
					},
				})

			}
		},
		esign_plugin(item, esign_psn_id) {
			if(!this.esignPlugin) return this.$util.Tips({ title: '不支持esignPlugin插件' });

			const flowId = item.flowId ? item.flowId : item.signFlowId
			const signerId = item.accountId ? item.accountId : esign_psn_id
			
			if(!flowId) return this.$util.Tips({ title: 'flowId为空' });
			if(!signerId) return this.$util.Tips({ title: 'signerId为空' });
			
			uni.navigateTo({
				url: `plugin://esign/esign?env=${this.esignEnv}&flowId=${flowId}&signerId=${signerId}`
			})
		},
		esign_H5(item) {
			const usr = encodeURIComponent(item.signUrl)
			uni.navigateTo({ url: '/pages/annex/web_view/index?url=' + usr })
		},
		esign_wxapp(item) {
			uni.navigateToMiniProgram({
			    appId: 'wx1cf2708c2de46337', // 公证签小程序APPID
			    path: '/pages/index/index', // webview页面地址
			    extraData: {
			        requestObj: { // 传入参数
						flowId: item.flowId, // 签署：signFlowId，认证授权：authFlowId
						accountId: item.accountId,
						env: this.esignEnv,
						type: this.esignType,
			        },
			        callbackObj: {  from:'esign', flag:'admin001' },
			    },
				fail(res) {
				    console.log('esign_wxapp_fail', res);
				},
			    success(res) {
			        console.log('esign_wxapp_success', res);
			    },
			    complete(res) {
			        console.log('esign_wxapp_complete', res);
			    },
			})
		},
		verify_esign_contract() {
			getSignContract(this.orderItem.id).then(res => {
				let title = null
				if(res.data.status == 'DRAFT') title = '草稿'
				if(res.data.status == 'SIGNING') title = '签署中'
				if(res.data.status == 'FINISH') title = '签署成功'
				if(res.data.status == 'UNDO') title = '撤销'
				if(res.data.status == 'TERMINATE') title = '终止'
				if(res.data.status == 'EXPIRE') title = '过期'
				if(res.data.status == 'REJECTED') title = '拒签'
				if(res.data.status == 'CANCELLED') title = '解约'
				this.$util.Tips({ title })
				if(this.contractOK) setTimeout(() => this.contractOK(), 1500)
			})
		},
		// 代扣签约查询
		verify_ato_withhold(id) {
			getWithholdSign(id).then(res => {
				let title = '待签约'
				if(res.data.status === 'SIGNED') title = '已签约'
				if(res.data.status === 'UNSIGNED') title = '未签约'
				if(res.data.status === 'TERMINATED') title = '已解约'
				if(res.data.status === 'TIMEOUT_CLOSE') title = '超时关闭'
				if(res.data.status === 'APPLY_TERMINATE') title = '申请解约'
				this.$util.Tips({ title:title, endtime:1000 })
				// 扣款中提示：代扣签约
				if(res.data.status === 'SIGNED'){
					uni.showLoading({
						title: '签约代扣成功，扣款中',
					})
					setTimeout(()=>{
						this.getOrderInfo()
						uni.hideLoading()
					},3000)
				}
				if(this.contractOK) setTimeout(() => this.contractOK(), 1500)
			})
		}
	
	}
}